<template>
    <div class="content">
        <div class="top">
            <ul>
                <li>
                    <SelectIpt :lists="stateIpt" ref="state">
                        <p>状态</p>
                    </SelectIpt>
                </li>
                <li>
                    <SelectIpt :lists="typeIpt" ref="type">
                        <p>住户类型</p>
                    </SelectIpt>
                </li>
                <li>
                    <SelectIpt :lists="build" ref="build">
                        <p>楼栋</p>
                    </SelectIpt>
                </li>
                <li>
                    <SelectIpt :lists="unit" ref="unit">
                        <p>单元</p>
                    </SelectIpt>
                </li>
                <li>
                    <SelectIpt :lists="floor" ref="floor">
                        <p>楼层</p>
                    </SelectIpt>
                </li>
                <!-- <li>
                    <SelectIpt>
                        <p>排序</p>
                    </SelectIpt>
                </li> -->
                <!-- <li>
                    <SelectIpt>
                        <p>年龄</p>
                    </SelectIpt>
                </li> -->
                <!-- <li>
                    <SelectIpt>
                        <p>住户标签</p>
                    </SelectIpt>
                </li> -->
                <li>
                    <SelectIpt :lists="cardType" ref="card">
                        <p>证件类型</p>
                    </SelectIpt>
                </li>
                <li>
                    <TextIpt ref="cardID">
                        <p>证件号</p>
                    </TextIpt>
                </li>
                <li>
                    <TextIpt ref="name">
                        <p>姓名</p>
                    </TextIpt>
                </li>
                <li>
                    <TextIpt ref="phone">
                        <p>手机号</p>
                    </TextIpt>
                </li>
            </ul>
            <div class="btn">
                <GreenBtn @click.native="search">查询</GreenBtn>
                <BlueBtn>新增</BlueBtn>
                <BlueBtn>批量导入</BlueBtn>
                <BlueBtn @click.native="reset">一键重置</BlueBtn>
                <BlueBtn>自助登记配置</BlueBtn>
            </div>
        </div>
        <div class="table">
            <el-table :data="isTable ? OwnerRoom.slice(pages, pages + 8) : filterRoom.slice(pages, pages + 8)" border
                style="width: 100%">
                <el-table-column v-for="column in tableColumns" :key="column.prop" :label="column.label"
                    :width="column.width || null">
                    <template slot-scope="scope">
                        {{ scope.row[column.prop] }}
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-button size="mini" @click="open(scope.$index, scope.row)">{{ scope.row.Islink == '启用' ? '停用'
                            : '启用' }}</el-button>
                        <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                        <el-button size="mini" @click="info(scope.$index, scope.row)">详情</el-button>
                        <el-button size="mini" type="danger"
                            @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="page">
                <div class="total-page">
                    <p>共<span>{{ Math.ceil(OwnerRoom.length / 8) }}</span>页/<span>{{ OwnerRoom.length }}</span>条数据</p>
                </div>
                <el-pagination background layout="prev, pager, next,jumper" @current-change="getPage" :page-size=8
                :current-page.sync=page :total=" isTable ? OwnerRoom.length : filterRoom.length"
                hide-on-single-page>
                </el-pagination>
            </div>
        </div>
        <el-dialog title="编辑" center: true :visible.sync="dialogVisible" width="35%" :before-close="handleClose"
            class="dialog">
            <!-- <p class="dialog-title">基本信息</p> -->
            <el-form ref="form" :model="form" :inline="true" label-width="80px" :disabled="isShow">
                <el-form-item label="姓名" :rules="{ required: true, message: '姓名不能为空' }" prop="name">
                    <el-input v-model="form.name"></el-input>
                </el-form-item>

                <el-form-item label="证件类型" :rules="{ required: true, message: '请选择证件类型' }" prop="cardType">
                    <el-select v-model="form.cardType" placeholder="请选择证件类型">
                        <el-option label="身份证" value="shanghai"></el-option>
                        <el-option label="护照" value="beijing"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="证件号" :rules="{ required: true, message: '证件号不能为空' }" prop="cardID">
                    <el-input v-model="form.cardID"></el-input>
                </el-form-item>
                <el-form-item label="住户类型" :rules="{ required: true, message: '请选择住户类型' }" prop="ownerType">
                    <el-select v-model="form.ownerType" placeholder="请选择住户类型">
                        <el-option label="业主" value="shanghai"></el-option>
                        <el-option label="租客" value="beijing"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="手机号" :rules="[
                    { required: true, message: '手机号不能为空' },
                    { message: '请输入正确的手机号', pattern: /^1[3-9]\d{9}$/, trigger: ['blur', 'change'] }
                ]" prop="phoneNum">
                    <el-input v-model="form.phoneNum"></el-input>
                </el-form-item>
                <div class="btn" v-show="!isShow">
                    <el-button @click="handleClose">取消</el-button>
                    <BlueBtn @click.native="onSubmit('form')">确定</BlueBtn>
                </div>
            </el-form>
        </el-dialog>
    </div>
</template>

<script>
import BlueBtn from '@/components/BlueBtn.vue';
import TextIpt from '@/components/TextIpt.vue';
import SelectIpt from '@/components/SelectIpt.vue';
import GreenBtn from '@/components/GreenBtn.vue';
import { mapActions, mapState } from 'vuex';
export default {
    components: {
        TextIpt,
        SelectIpt,
        BlueBtn,
        GreenBtn
    },
    data() {
        return {
            //过滤的数据
            filterRoom: [],
            //用于判断显示那个数据
            isTable: true,
            //输入框数组
            stateIpt: ['停用', '启用'],
            typeIpt: ['业主', '租客'],
            //楼栋
            build: ['楼栋A', '楼栋B', '楼栋C', '楼栋D'],
            //单元
            unit: ['1单元', '2单元', '3单元'],
            //楼层
            floor: ['一层', '二层', '三层'],
            //房间
            room: ['101', '102', '201', '202', '301', '302'],
            cardType: ['身份证', '护照'],
            //判断数据是否发送改变
            // dataChange:0,
            //弹框
            dialogVisible: false,
            //是否可用
            isShow: false,
            //page
            pages: 0,
            page:0,
            //过滤数据
            lists: [],
            tableColumns: [
                { prop: 'Owner', label: '姓名', width: 80 },
                { prop: 'Type', label: '类型', width: 80 },
                { prop: 'TypeID', label: '证件类型', width: 100 },
                { prop: 'CardNum', label: '证件号', width: 200 },
                { prop: 'Phone', label: '手机号', width: 150 },
                { prop: 'BuildingName', label: '楼栋', width: 100 },
                { prop: 'UnitName', label: '单元', width: 150 },
                { prop: 'FloorNumber', label: '楼层', width: 80 },
                { prop: 'RoomNumber', label: '房屋号', width: 100 },
                { prop: 'AddDate', label: '添加时间', width: 120 },
                { prop: 'AddMan', label: '添加人', width: 120 },
                { prop: 'Islink', label: '状态', width: 70 },

            ],
            //记录下标索引
            index: 0,
            //表单数据
            form: {
                name: '',
                cardType: '',
                cardID: '',
                ownerType: '',
                phoneNum: '',
                RoomID: 1,
            }
        }
    },
    // watch: {
    //     form: {
    //         handler(val, oldval) {
    //         //    this.dataChange=!this.dataChange
    //         //    console.log(val,9999);
    //         //    console.log(oldval,3333);
    //         },
    //         deep: true
    //     }
    // },
    methods: {
        //一键重置
        reset(){
            this.$refs.type.value=''
            this.$refs.state.value=''
            this.$refs.build.value=''
            this.$refs.unit.value=''
            this.$refs.floor.value=''
            this.$refs.card.value=''
            this.$refs.cardID.input=''
            this.$refs.name.input=''
            this.$refs.phone.input=''
        },
        //点击查询按钮
        search() {
            this.isTable = false
            const serach = {}
            this.pages = 0
            this.page = 0

            if (this.$refs.state.value) {
                serach.IsLink = this.$refs.state.value
            }
            if (this.$refs.type.value) {
                serach.Type = this.$refs.type.value
            }
            if (this.$refs.build.value) {
                serach.BuildName = this.$refs.build.value
            }
            if (this.$refs.unit.value) {
                serach.UnitName = this.$refs.unit.value
            }
            if (this.$refs.floor.value) {
                serach.FloorNumber = this.$refs.floor.value
            }
            if (this.$refs.card.value) {
                serach.TypeID = this.$refs.card.value
            }
            if (this.$refs.cardID.input) {
                serach.CardNum = this.$refs.cardID.input
            }
            if (this.$refs.name.input) {
                serach.Owner = this.$refs.name.input
            }
            if (this.$refs.phone.input) {
                serach.PhoneNumber = this.$refs.phone.input
            }

            this.filterRoom = this.OwnerRoom.filter(item => {
                // 检查Status是否匹配
                if (serach.IsLink && item.Islink != serach.IsLink) {
                    return false; // 如果不匹配，则排除该房间
                }
                if (serach.Type && item.Type !== serach.Type) {
                    return false; // 如果不匹配，则排除该房间
                }
                if (serach.BuildName && item.BuildingName !== serach.BuildName) {
                    return false; // 如果不匹配，则排除该房间
                }
                if (serach.UnitName && item.UnitName !== serach.UnitName) {
                    return false; // 如果不匹配，则排除该房间
                }
                if (serach.FloorNumber && item.FloorNumber !== serach.FloorNumber) {
                    return false; // 如果不匹配，则排除该房间
                }
                if (serach.TypeID && item.TypeID !== serach.TypeID) {
                    return false; // 如果不匹配，则排除该房间
                }

                if (serach.Owner && !item.Owner.includes(serach.Owner)) {
                    return false; // 如果不匹配，则排除该房间
                }
                if (serach.CardNum && !item.CardNum.includes(serach.CardNum)) {
                    return false; // 如果不匹配，则排除该房间
                }

                if (serach.PhoneNumber && !item.PhoneNumber.includes(serach.PhoneNumber)) {
                    return false; // 如果不匹配，则排除该房间
                }
                // 如果所有条件都匹配或为空（表示用户没有为该字段指定筛选条件），则返回true以包含该房间
                return true;

            })

        },
        //点击编辑弹框的确认
        onSubmit(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.updateAll()
                    this.OwnerRoom[this.index].Owner = this.form.name
                    this.OwnerRoom[this.index].TypeID = this.form.cardType
                    this.OwnerRoom[this.index].CardNum = this.form.cardID
                    this.OwnerRoom[this.index].Type = this.form.ownerType
                    this.OwnerRoom[this.index].Phone = this.form.phoneNum
                    this.dialogVisible = false
                } else {
                    return false;
                }
            });
        },
        info(index, row) {
            this.handleEdit(index, row)
            this.isShow = true
        },
        //弹窗关闭
        handleClose(done) {
            this.$confirm('确认关闭？')
                .then(_ => {
                    this.dialogVisible = false
                })
                .catch(_ => { });
        },
        ...mapActions(['getList']),
        //get 当前页
        getPage(page) {
            this.pages = 8 * (page - 1)
        },
        handleEdit(index, row) {
            if (this.isShow) {
                this.isShow = false
            }
            this.form.name = row.Owner
            this.form.cardType = row.TypeID
            this.form.cardID = row.CardNum
            this.form.ownerType = row.Type
            this.form.phoneNum = row.Phone
            this.form.RoomID = row.RoomID
            this.index = index + this.pages
            this.dialogVisible = true


        },
        handleDelete(index, row) {
            console.log(index, row);
        },
        //更新用户状态停用,启用
        updateStatus(id, str) {
            fetch('http://127.0.0.1/user/state', {
                method: 'POST',
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`,
                    'Content-Type': 'application/json' // 如果需要发送 JSON 数据，则包含此行 // 设置请求头
                },
                body: JSON.stringify({
                    id,
                    str
                })
            }).then(res => res.json()).then(res1 => {
                this.$message({
                    type: 'success',
                    message: '停用(启用)成功!'
                });
            }).catch(err => {
                console.log(err)
            })
        },
        //更新所有的数据
        updateAll() {
            fetch('http://127.0.0.1/user/allUpdate', {
                method: 'POST',
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`,
                    'Content-Type': 'application/json' // 如果需要发送 JSON 数据，则包含此行 // 设置请求头
                },
                body: JSON.stringify({
                    ...this.form
                })
            }).then(res => res.json()).then(res1 => {
                this.$message({
                    type: 'success',
                    message: '修改成功!'
                });
            }).catch(err => {
                console.log(err)
            })
        },
        //停用弹窗
        open(index, row) {
            this.$confirm('确认停用？停用后住户将不能登录移动端（app、小程序）但不影响住户门禁权限。', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                row.Islink = row.Islink == '启用' ? '停用' : '启用'
                this.updateStatus(row.RoomID, row.Islink)
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消'
                });
            });
        }
    },
    computed: {
        ...mapState(['allData', 'OwnerRoom'])
    },
    mounted() {
        if (this.allData.length == 0) {
            this.getList()
        }


        // this.lists = this.allData.filter(item => item.Owner != null)
    }
}
</script>

<style scoped>
.dialog>>>.el-dialog {
    margin-top: 0 !important;
}

.el-dialog__wrapper {
    display: flex;
    align-items: center;
    justify-content: center;
}

.dialog .btn {
    margin-top: 20px;
    text-align: right;
}

.btn>>>.el-button--default {
    height: 32px;
    width: 94px;
    padding: 0;
    margin-right: 20px;
}
.btn >>> button{
    line-height: 30px;
}

.dialog-title {
    font-size: 14px;
    color: #000;
    padding-bottom: 15px;
    margin-bottom: 15px;
    /* border-bottom: 1px solid #cacaca; */
}

.table>>>.el-table {
    min-height: 500px;
}

.page {
    display: flex;
    align-items: center;
    justify-content: end;
    margin-top: 20px;
}

.page>>>button {
    min-width: 35px !important;
    height: 25px;
    line-height: 25px;
    border-radius: 3px !important;
    border: 1px solid rgba(215, 215, 215, 1);
    background: #fff !important;
}

.page>>>.active {
    border-color: rgba(26, 135, 254, 1) !important;
    background-color: rgba(26, 135, 254, 1) !important;
    color: #fff !important;
}

.page>>>.el-pager li {
    min-width: 35px !important;
    height: 25px;
    line-height: 25px;
    border-radius: 3px !important;
    border: 1px solid rgba(215, 215, 215, 1);
    font-size: 12px;
    color: #999;
    font-weight: normal !important;
    background: #fff;
}

.total-page span {
    color: #FF3C2C;
}

.total-page {
    font-size: 12px;
    color: #666;
}

.table>>>.cell {
    text-align: center;
}

.table {
    padding: 20px 20px 50px;
    background: #fff;
    border-radius: 4px;
    margin-top: 10px;
}

.btn>>>span {
    font-size: 14px;
}

.top li p {
    white-space: nowrap;
    text-align: right;
    min-width: 52px;
    font-size: 13px;
    color: #666;
}

.top ul {
    display: flex;
    flex-wrap: wrap;
}

.top li {
    margin-right: 30px;
    margin-bottom: 20px;
}

.top {
    background: #fff;
    border-radius: 4px;
    padding: 20px 25px;
}
</style>